<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="horizontal" >
          <a-row :gutter="8">
            <a-col :md="8" :sm="24">
              <a-form-item label="角色名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="queryParam.roleName" placeholder="支持模糊查询"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="角色类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select v-model="queryParam.roleTypes" mode="multiple" placeholder="支持多选" allowClear >
                  <a-select-option v-for="item in dictData.roleType" :key="item.dictKey" :value="item.dictKey">{{ item.dictValue }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select v-model="queryParam.status" placeholder="请选择" allowClear default-value="1">
                    <a-select-option value="0">禁用</a-select-option>
                    <a-select-option value="1">启用</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="() =>{this.findRoleListBtn()}">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => {this.clearAll()}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <vxe-grid
        class="vxe-table-antd"
        resizable
        show-overflow
        ref="roleListTable"
        stripe
        border
        highlight-hover-row
        highlight-current-row
        highlight-hover-column
        highlight-current-column
        highlight-cell
        row-id="roleId"
        height="400"
        size="small"
        :columns="tableColumn"
        :data="tableData"
        :loading="loading"
        :start-index="(tablePage.currentPage - 1) * tablePage.pageSize"
        :pager-config="tablePage"
        :radio-config="{ trigger: 'row'}"
        :edit-config="{trigger: 'click', mode: 'cell'}"
        @page-change="handlePageChange"
        @radio-change="radioChangeEvent">
      </vxe-grid>
      <a-modal
        :title="modalTitle"
        centered
        style="top: 10px;"
        width="50%"
        destroyOnClose
        v-model="visible"
        @ok="saveRole"
        @cancel="cancelRole"
        cancelText="关闭"
        okText="保存"
      >
        <role-form ref="rolePage" :roleInfo="selectRow" />
      </a-modal>
      <a-modal
        title="用户授权"
        style="top: 10px;"
        centered
        width="85%"
        destroyOnClose
        v-model="roleUserVisible"
      >
        <template slot="footer">
          <a-button @click="closeRoleUser" >
            关闭
          </a-button>
          <a-button type="primary" @click="saveUser" :disabled="saveUserDisable">
            授权
          </a-button>
          <a-button type="danger" @click="deleteUser" :disabled="deleteUserDisable">
            取消授权
          </a-button>
        </template>
        <role-user-form ref="roleUserPage" @roleUserBtn="setRoleUserBtn" :roleInfo="selectRow" />
      </a-modal>
      <a-modal
        title="组织授权"
        centered
        style="top: 10px;"
        width="450px"
        destroyOnClose
        v-model="roleOrgVisible"
        @ok="saveOrg"
        cancelText="关闭"
        okText="保存"
      >
        <org-tree-form ref="orgTreePage" :roleId="roleId" />
      </a-modal>
      <a-modal
        title="资源授权"
        centered
        style="top: 10px;"
        width="450px"
        destroyOnClose
        v-model="roleRouterFuncVisible"
        @ok="saveRouterFunc"
        cancelText="关闭"
        okText="保存"
      >
        <router-func-tree-form ref="routerFuncTreePage" :roleId="roleId" />
      </a-modal>
    </a-card>
    <!-- fixed footer toolbar -->
    <footer-tool-bar>
      <a-button style="margin-left: 8px;" type="primary" icon="plus" @click="() =>{this.openRoleRouterFuncModel()}">资源分配</a-button>
      <a-button style="margin-left: 8px;" type="primary" icon="plus" @click="() =>{this.openRoleOrgModel()}">组织分配</a-button>
      <a-button style="margin-left: 8px;" type="primary" icon="plus" @click="() =>{this.openRoleUserModel()}">用户分配</a-button>
      <a-button style="margin-left: 8px" type="primary" icon="plus" @click="() =>{this.addRole()}">创建角色</a-button>
      <a-button style="margin-left: 8px;" type="primary" icon="edit" @click="() =>{this.editRole()}">编辑编辑</a-button>
      <a-button style="margin-left: 8px" type="danger" icon="minus" @click="() =>{this.deleteRole()}">删除</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
import { getBatchDict,getRoleList, editRoleStatus, deleteRole, addRole, editRole, saveRoleUser, deleteRoleUser, saveRoleOrg, saveRoleRouterFunc } from "@/services/system/api"
import FooterToolBar from '@/components/FooterToolbar'
import modal from 'ant-design-vue/es/modal'
import RoleForm from '@/pages/system/form/RoleForm'
import RoleUserForm from '@/pages/system/form/RoleUserForm'
import OrgTreeForm from '@/pages/system/form/OrgTreeForm'
import RouterFuncTreeForm from '@/pages/system/form/RouterFuncTreeForm'
import moment from 'moment'
export default {
  name: 'RoleManager',
  components: {
    FooterToolBar,
    RoleForm,
    RoleUserForm,
    OrgTreeForm,
    RouterFuncTreeForm
  },
  data () {
    return {
      description: '角色管理',
      dictData: {},
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      form: null,
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      loading: false,
      tablePage: {
        total: 0,
        currentPage: 1,
        pageNum: 1,
        pageSize: 20
      },
      tableColumn: [
        { type: 'radio', width: 40, fixed: 'left', align: 'center', slots: { header: () => { return [ <a-tooltip placement="top" title="取消选择"><a-icon type="stop" theme="twoTone" onClick={ this.clearRadioRowEevnt }/></a-tooltip> ] } } },
        { type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号' },
        { field: 'roleId', title: '角色Id', fixed: 'left', visible: false, align: 'center', width: 150 },
        { field: 'roleName', title: '角色名称', align: 'center', fixed: 'left', width: 250 },
        { field: 'status', title: '状态', align: 'center', editRender: { name: 'ASwitch', type: 'visible', props: { checkedChildren: '启用', unCheckedChildren: '禁用' }, events: { change: this.onStatusChange } }, width: 80 },
        { field: 'parentId', title: '父角色Id', visible: false, align: 'center', width: 200 },
        { field: 'roleType', title: '角色类型', visible: false, align: 'center', width: 100 },
        { field: 'roleTypeName', title: '角色类型', align: 'center', width: 150 },
        { field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: 350 }
      ],
      tableData: [],
      selectRow: null,
      modalTitle: '操作',
      roleUserVisible: false,
      saveUserDisable: false,
      deleteUserDisable: true,
      roleOrgVisible: false,
      roleId: null,
      roleRouterFuncVisible: false
    }
  },
  created () {
    // 数据初始化
    // 数据字典初始化
    const params = {}
    params.dictFields = 'roleType'
    this.$http.post(getBatchDict,params).then(res => {
      this.dictData = res.result
    })
    // 初始化组织列表
    this.findRoleList()
  },
  methods: {
    moment,
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    radioChangeEvent ({ row }) {
      this.roleId = row.roleId
      this.selectRow = row
      console.log('单选事件')
    },
    clearRadioRowEevnt () {
      this.selectRow = null
      this.$refs.roleListTable.clearRadioRow()
    },
    handlePageChange ({ currentPage, pageSize }) {
      this.tablePage.pageNum = currentPage
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.findRoleList()
    },
    findRoleListBtn () {
      this.tablePage.pageNum = 1
      this.tablePage.currentPage = 1
      this.findRoleList()
    },
    // 角色列表查询
    findRoleList () {
      this.loading = true
      const params = Object.assign(this.queryParam, this.tablePage)
      params.permissionFlag = false
      setTimeout(() => {
        this.$http.post(getRoleList,params).then((res) => {
          const data = res.result.list
          data.forEach((item) => {
            if (item.status === '1') {
              item.status = true
            } else {
              item.status = false
            }
          })
          this.tableData = data
          this.tablePage.total = res.result.total
          this.tablePage.pageNum = res.result.pageNum
          this.tablePage.currentPage = res.result.pageNum
          this.tablePage.pageSize = res.result.pageSize
          this.loading = false
          this.selectRow = null
          this.roleId = null
        }).catch(() => {
          this.loading = false
        })
      }, 200)
    },
    // 启用/禁用用户
    onStatusChange ({ row }, value) {
      const params = {}
      params.roleId = row.roleId
      params.status = '0'
      let text = '禁用'
      if (value) {
        text = '启用'
        params.status = '1'
      }
      setTimeout(() => {
        this.$http.post(editRoleStatus,params).then(() => {
          modal.info({ title: '成功提示', content: text + '成功' })
        }).catch(() => {
        })
      }, 200)
    },
    addRole () {
      this.clearRadioRowEevnt()
      this.modalTitle = '新增角色信息'
      this.visible = true
    },
    editRole () {
      if (this.selectRow) {
        this.modalTitle = '修改角色信息'
        this.visible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要修改的数据' })
      }
    },
    saveRole () {
      // 表单验证
      const { $refs: { rolePage } } = this
      const roleForm = new Promise((resolve, reject) => {
        rolePage.form.validateFields((err, values) => {
          if (err) {
            reject(err)
            return
          }
          resolve(values)
        })
      })
      this.errors = []
      Promise.all([roleForm]).then(values => {
        if (values && values.length > 0) {
          const role = values[0]
          if (role.roleId) {
            setTimeout(() => {
              this.$http.post(editRole,role).then((res) => {
                modal.info({ title: '成功提示', content: '修改成功' })
                this.visible = false
                const data = [...this.tableData]
                if (res.result.status === '1') {
                  res.result.status = true
                } else {
                  res.result.status = false
                }
                let i
                data.forEach((item, index, arr) => {
                  if (item.roleId === res.result.roleId) {
                    i = index
                    arr.splice(index, 1, res.result)
                    return item
                  }
                })
                this.tableData = data
                this.selectRow = res.result
                this.roleId = res.result.roleId
                this.$refs.roleListTable.setRadioRow(this.tableData[i], true)
                this.$refs.roleListTable.setCurrentRow(this.tableData[i], true)
              }).catch(() => {
              })
            }, 200)
          } else {
            setTimeout(() => {
              this.$http.post(addRole,role).then((res) => {
                modal.info({ title: '成功提示', content: '新增成功' })
                this.visible = false
                this.queryParam.roleName = res.result.roleName
                this.findRoleList()
              }).catch(() => {
              })
            }, 200)
          }
        }
      }).catch(() => {
        const errors = Object.assign({}, rolePage.form.getFieldsError())
        const tmp = { ...errors }
        this.errorList(tmp)
      })
    },
    cancelRole () {
      const role = this.selectRow
      if (role) {
        const data = [...this.tableData]
        if (role.status === '1') {
          role.status = true
        } else {
          role.status = false
        }
        data.forEach((item, index, arr) => {
          if (item.roleId === role.roleId) {
            arr.splice(index, 1, role)
            return item
          }
        })
        this.tableData = data
      }
      this.visible = false
    },
    errorList (errors) {
      if (!errors || errors.length === 0) {
        return
      }
      this.errors = Object.keys(errors)
        .filter(key => errors[key])
        .map(key => ({
          key: key,
          message: errors[key][0]
        }))
    },
    deleteRole () {
      if (this.selectRow) {
        const params = {}
        params.roleId = this.selectRow.roleId
        setTimeout(() => {
          this.$http.post(deleteRole,params).then(() => {
            modal.info({ title: '成功提示', content: '删除用户成功' })
            this.findRoleList()
          }).catch(() => {
          })
        }, 100)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要删除的数据' })
      }
    },
    closeRoleUser () {
      this.roleUserVisible = false
    },
    openRoleUserModel () {
      // 打开添加用户页面
      if (this.selectRow) {
        this.roleId = this.selectRow.roleId
        this.saveUserDisable = false
        this.deleteUserDisable = true
        this.roleUserVisible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的角色' })
      }
    },
    saveUser () {
      const users = this.$refs.roleUserPage.userChecked
      const roleId = this.selectRow.roleId
      if (users) {
        if (users.length <= 0) {
          modal.warn({ title: '提示', content: '请先勾选需要授权的用户' })
          return false
        }
      } else {
        modal.warn({ title: '提示', content: '请先勾选需要授权的用户' })
        return false
      }
      const userIds = []
      users.forEach((item) => {
        userIds.push(item.userId)
      })
      const params = {}
      params.roleId = roleId
      params.userIds = userIds
      setTimeout(() => {
        this.$http.post(saveRoleUser,params).then(() => {
          modal.info({ title: '成功提示', content: '授权成功' })
          this.$refs.roleUserPage.findUserList()
          this.$refs.roleUserPage.clearUserChecked()
        }).catch(() => {
        })
      }, 10)
    },
    deleteUser () {
      if (this.selectRow) {
        const checkedUser = this.$refs.roleUserPage.userChecked
        if (checkedUser && checkedUser.length > 0) {
          const userIds = []
          checkedUser.forEach((item) => {
            userIds.push(item.userId)
          })
          const params = {}
          params.userIds = userIds
          params.roleId = this.selectRow.roleId
          setTimeout(() => {
            this.$http.post(deleteRoleUser,params).then(() => {
              modal.info({ title: '成功提示', content: '删除成功' })
              this.$refs.roleUserPage.findUserList()
              this.$refs.roleUserPage.clearCheck()
            }).catch(() => {
            })
          }, 10)
        } else {
          modal.warn({ title: '提示', content: '请先勾选需要删除的用户' })
        }
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的角色' })
      }
    },
    setRoleUserBtn (value) {
      if (value) {
        if (value === '1') {
          this.saveUserDisable = false
          this.deleteUserDisable = true
        } else if (value === '2') {
          this.saveUserDisable = true
          this.deleteUserDisable = false
        } if (value === '3') {
          this.saveUserDisable = true
          this.deleteUserDisable = true
        }
      } else {
        this.saveUserDisable = false
        this.deleteUserDisable = true
      }
    },
    openRoleOrgModel () {
      // 打开组织授权页面
      if (this.roleId) {
        this.roleOrgVisible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的角色' })
      }
    },
    saveOrg () {
      if (this.roleId) {
        const checkedObject = this.$refs.orgTreePage.checkedOrgKeys
        const checkedkeys = checkedObject.checked
        const params = {}
        params.orgIds = checkedkeys
        params.roleId = this.roleId
        setTimeout(() => {
          this.$http.post(saveRoleOrg,params).then(() => {
            modal.info({ title: '成功提示', content: '授权成功' })
            this.roleOrgVisible = false
          }).catch(() => {
          })
        }, 10)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的角色' })
      }
    },
    openRoleRouterFuncModel () {
      // 打开资源授权页面
      if (this.roleId) {
        this.roleRouterFuncVisible = true
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的角色' })
      }
    },
    saveRouterFunc () {
      if (this.roleId) {
        const checkedkeys = this.$refs.routerFuncTreePage.checkedKeys
        const params = {}
        params.objectIds = checkedkeys
        params.roleId = this.roleId
        setTimeout(() => {
          this.$http.post(saveRoleRouterFunc,params).then(() => {
            modal.info({ title: '成功提示', content: '授权成功' })
            this.roleRouterFuncVisible = false
          }).catch(() => {
          })
        }, 10)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要操作的角色' })
      }
    },
    clearAll () {
      this.queryParam = {}
      this.findRoleList()
      setTimeout(() => {
        this.clearRadioRowEevnt()
        this.$refs.roleListTable.clearSelection()
        this.$refs.roleListTable.clearSelectReserve()
      }, 50)
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
